<!-- 
    liaotuo 
    2016.09.25 
    随机轨迹生成
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=百度地图API开发者密钥AK">
</script>
<title>轨迹动态展示</title>
</head>
<body>
<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
//数据准备,  
var points = [];//原始点信息数组  
var bPoints = [];//百度化坐标数组。用于更新显示范围。  
//创建标注点并添加到地图中
function addMarker(points) {
	//循环建立标注点
	for(var i=0, pointsLen = points.length; i<pointsLen; i++) {
		var point = new BMap.Point(points[i].lng, points[i].lat); //将标注点转化成地图上的点
		var marker = new BMap.Marker(point); //将点转化成标注点
		map.addOverlay(marker);  //将标注点添加到地图上
		//添加监听事件
		(function() {
			var thePoint = points[i];
			marker.addEventListener("click",
				function() {
				showInfo(this,thePoint);
			});
		 })();  
	}
}

//添加线  
function addLine(points){  
  
    var linePoints = [],pointsLen = points.length,i,polyline;  
    if(pointsLen == 0){  
        return;  
    }  
    // 创建标注对象并添加到地图     
    for(i = 0;i <pointsLen;i++){  
        linePoints.push(new BMap.Point(points[i].lng,points[i].lat));  
    }  
  
    polyline = new BMap.Polyline(linePoints, {strokeColor:"green", strokeWeight:5, strokeOpacity:1});   //创建折线  
    map.addOverlay(polyline);   //增加折线  
}

//随机生成新的点，加入到轨迹中。  
function dynamicLine(){  
    var lng = 112+getRandom(100)*0.01;  
    var lat = 26+getRandom(100)*0.01;  
    var id = getRandom(1000);  
    var point = {"lng":lng,"lat":lat,"status":1,"id":id}  
    var makerPoints = [];  
    var newLinePoints = [];  
    var len;  
  
    makerPoints.push(point);              
    addMarker(makerPoints);//增加对应该的轨迹点  
    points.push(point);  
    bPoints.push(new BMap.Point(lng,lat));  
    len = points.length;  
    newLinePoints = points.slice(len-2, len);//最后两个点用来画线。  
  
    addLine(newLinePoints);//增加轨迹线  
    setZoom(bPoints);  
    setTimeout(dynamicLine, 1000);  
}  

// 获取随机数  
function getRandom(n){  
    return Math.floor(Math.random()*n+1)  
}  

//根据点信息实时更新地图显示范围，让轨迹完整显示。设置新的中心点和显示级别  
function setZoom(bPoints){  
    var view = map.getViewport(eval(bPoints));  
    var mapZoom = view.zoom;   
    var centerPoint = view.center;   
    map.centerAndZoom(centerPoint,mapZoom);  
}  

//创建地图
var map = new BMap.Map("allmap");    

map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);  // 设置中心点
map.centerAndZoom( "衡阳");
map.setCurrentCity("衡阳");          //设置为衡阳
map.addControl(new BMap.MapTypeControl()); //可拖拽  
map.enableScrollWheelZoom(true);  //滚轮实现方法缩小 
    dynamicLine();


</script>
